package com.onlinelibrary.activities.reply;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Application;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.databinding.BindingAdapter;
import androidx.databinding.library.baseAdapters.BR;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.google.android.material.snackbar.Snackbar;
import com.onlinelibrary.activities.App;
import com.onlinelibrary.adapter.ReplyAdapter;
import com.onlinelibrary.bean.CRBean;
import com.onlinelibrary.databinding.ActivityReplyBinding;
import com.onlinelibrary.utils.Http;
import com.onlinelibrary.view.PullingLayout;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ReplyVM extends AndroidViewModel {
    @SuppressLint("StaticFieldLeak")
    private static ReplyActivity replyActivity;
    private static int count=0;
    @SuppressLint("StaticFieldLeak")
    private static ActivityReplyBinding binding;
    private static final List<CRBean> data=new ArrayList<>();

    public static MutableLiveData<String>commentName=new MutableLiveData<>(),
            commentContent=new MutableLiveData<>(),
            commentTime=new MutableLiveData<>();

    public ReplyVM(@NonNull Application application) {
        super(application);
        commentName.setValue(App.commentName);
        commentContent.setValue(App.commentContent);
        commentTime.setValue(App.commentTime);
    }
    public void setBinding(ActivityReplyBinding binding, ReplyActivity replyActivity) {
        ReplyVM.replyActivity=replyActivity;
        ReplyVM.binding=binding;
        binding.setVariable(BR.adp,new ReplyAdapter(replyActivity,data));
        binding.replyList.setOnItemClickListener((parent, view, position, id) -> {
            CRBean bean = data.get(position);
            if (App.sp.getString("account","").equals(bean.email)){
                AlertDialog.Builder dia=new AlertDialog.Builder(replyActivity);
                dia.setTitle("提示").setMessage("这是您的回复，确定删除吗？").setPositiveButton("删除", (dialog, which) ->
                        Http.get("comment/?type=delete_reply&name="+bean.name+"&time="+bean.time, new Callback() {
                            @Override
                            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                                refresh(null);
                            }
                            @Override
                            public void onResponse(@NotNull Call call, @NotNull Response response) {
                                refresh(null);
                            }})).setNeutralButton("关闭",null).show();
            }
        });
        App.autoLoginCheck(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) { }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) {
                replyActivity.runOnUiThread(() -> {
                    try {
                        assert response.body() != null;
                        String res = response.body().string();
                        if (res.equals("验证成功")){
                            App.hasLogin=true;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
        });
        refresh(null);
    }
    public static void addReply(View v){
        if (!App.hasLogin){
            Snackbar.make(v,"请先登录",Snackbar.LENGTH_LONG).show();
            return;
        }
        AlertDialog.Builder dia=new AlertDialog.Builder(replyActivity);
        EditText view=new EditText(replyActivity);
        view.setHint("回复点什么吧...");
        dia.setTitle("回复").setView(view).setPositiveButton("回复", (dialog, which) -> {
            try {
                JSONObject jo=new JSONObject();
                jo.put("type","create_reply");
                jo.put("name",App.sp.getString("name","Tourist"));
                jo.put("email",App.sp.getString("account", "defaultEmail"));
                jo.put("content",view.getText().toString());
                jo.put("father_name",App.commentName);
                jo.put("father_time",App.commentTime);
                jo.put("father_content",App.commentContent);
                jo.put("visible",App.is_staff);
                Http.post(jo, "comment/", new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) { }
                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) {
                        replyActivity.runOnUiThread(() -> {
                            refresh(null);
                           if (!App.is_staff){
                               Snackbar.make(v,"添加完成,请请等待审核",Snackbar.LENGTH_LONG).show();
                           }else {
                               Snackbar.make(v,"添加完成",Snackbar.LENGTH_LONG).show();
                           }
                        });
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }).setNeutralButton("取消",null).setCancelable(false).show();
    }
    @BindingAdapter("bindPull")
    public static void bindPull(PullingLayout pullingLayout, ReplyVM replyVM){
        pullingLayout.setPullDownEnabled(true);
        pullingLayout.setPullUpEnabled(true);
        pullingLayout.setOnRefreshListener(ReplyVM::refresh);
        pullingLayout.setOnLoadMoreListener(pullToLoadMoreLayout -> Http.get("comment/?type=get_reply&start="+count+"&end="+(count+20)+"&father_name="+App.commentName+"&father_time="+App.commentTime, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                replyActivity.runOnUiThread(() -> pullToLoadMoreLayout.loadmoreFinish(1));
            }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                try {
                    JSONObject res = new JSONObject(response.body().string());
                    if (res.getString("data").equals("No Reply")){
                        replyActivity.runOnUiThread(() -> pullToLoadMoreLayout.loadmoreFinish(2));
                    }else {
                        JSONArray ja = res.getJSONArray("data");
                        for (int i = 0; i < ja.length(); i++){
                            JSONObject jo = ja.getJSONObject(i);
                            data.add(new CRBean(false,jo.getString("time"),jo.getString("name"),jo.getString("content"),jo.getString("email")));
                        }
                        replyActivity.runOnUiThread(() -> {
                            binding.getAdp().notifyDataSetChanged();
                            count=data.size();
                            pullToLoadMoreLayout.loadmoreFinish(0);
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }));
    }
    private static void refresh(PullingLayout pullToRefreshLayout) {
        count=0;
        data.clear();
        Http.get("comment/?type=get_reply&start=0&end=20&father_name="+App.commentName+"&father_time="+App.commentTime, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                replyActivity.runOnUiThread(() -> {
                    if (pullToRefreshLayout!=null)pullToRefreshLayout.refreshFinish(1);
                });
            }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                try {
                    JSONObject res = new JSONObject(response.body().string());
                    if (res.getString("data").equals("No Reply")){
                        replyActivity.runOnUiThread(() -> {
                            if (pullToRefreshLayout!=null)pullToRefreshLayout.refreshFinish(2);
                        });
                    }else {
                        JSONArray ja = res.getJSONArray("data");
                        for (int i = 0; i < ja.length(); i++) {
                            JSONObject jo = ja.getJSONObject(i);
                            data.add(new CRBean(false,jo.getString("time"),jo.getString("name"),jo.getString("content"),jo.getString("email")));
                        }
                        replyActivity.runOnUiThread(() -> {
                            binding.getAdp().notifyDataSetChanged();
                            count=data.size();
                            if (pullToRefreshLayout!=null)pullToRefreshLayout.refreshFinish(0);
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}